import { DatasetListItem } from '@/common';
import { Permission } from '@/types/share-link';
import { findParentIdArray } from '@/utils/tree';

export const cvpermission = (
  allDatasets: DatasetListItem[],
  permissions: Permission[] | undefined,
) => {
  if (!permissions) {
    return [];
  }
  const datas: Array<string[]> = [];

  // 遍历权限数据，按照resource_type和resource_id进行组织
  permissions.forEach((p) => {
    const array = findParentIdArray(allDatasets, p.resource_id);
    if (array) {
      datas.push([...array, p.resource_id]);
    }
  });

  return datas;
};

export const removeDuplicates = (
  arr: string[][],
  permissions: Permission[],
  returnName = false,
): string[][] => {
  // 使用 Set 来存储唯一的字符串化子数组
  const seen = new Set<string[]>();

  // 过滤原数组，确保每个子数组的组合是唯一的
  const result = arr.filter((subArray, index) => {
    // 将子数组排序并字符串化
    const current = subArray.join('');
    // 判断是否存在重复项
    if (
      arr.some((item, i) => {
        const compare = item.join('');
        return index !== i && compare.startsWith(current);
      })
    ) {
      return false; // 如果存在，表示重复，过滤掉
    }
    if (returnName) {
      const names = convIdToName(subArray, permissions);
      seen.add(names); // 如果不存在，添加到 Set 中并保留该子数组
    } else {
      seen.add(subArray);
    }
    return true;
  });

  return Array.from(seen);
};

export const convIdToName = (arrs: string[], permissions: Permission[]) => {
  const names: string[] = [];
  arrs.forEach((id) => {
    const dataset = permissions.find((dataset) => dataset.resource_id === id);
    if (dataset) {
      names.push(dataset.name || dataset.resource_name || '');
    }
  });
  return names;
};
